package com.wanxin.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Enumeration;


@Controller
public class MyController {
    /**
     * 获取session中的数据
     *
     * @param session
     * @return
     */
    @RequestMapping("demoSession")
    @ResponseBody
    public String demoSession(HttpSession session) {
        Enumeration<String> names = session.getAttributeNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            Object value = session.getAttribute(name);
            //打印结果
            System.out.println(name + "----" + value);
        }
        return "Session取值";
    }


    /**
     * @return 跳转登入页面
     */
    @RequestMapping("login")
    public String loginPage() {
        return "login";
    }


    /**
     * @return 登入成功页面
     */
    @RequestMapping("main")
    public String loginYes() {
        return "main";
    }


    /**
     * //用户登入
     *
     * @param uname
     * @param pwd
     * @param remember
     * @return
     */
    @PostMapping("userLogin")
    @ResponseBody
    public String userLogin(String uname, String pwd, @RequestParam(defaultValue = "false") Boolean remember) {
        //获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //创建对象存储认证信息
        AuthenticationToken token = new UsernamePasswordToken(uname, pwd, remember);
        //调用shiro的login方法完成登入验证
        try {
            subject.login(token);
            return "登入成功";
        } catch (UnknownAccountException e) {
            return "账号不存在";
        } catch (IncorrectCredentialsException e) {
            return "密码错误";
        } catch (ExcessiveAttemptsException e) {
            return "登入失败 . 账号锁定10分钟";
        }
    }
}
